<template>
  <div class="resource-property-manager">
    <div class="manager-header">
      <h2>资源属性管理</h2>
      <div class="header-actions">
        <Button type="primary" @click="saveSchema" :loading="saving">
          <IconifyIcon icon="ant-design:save-outlined" />
          保存结构
        </Button>
        <Button @click="previewForm">
          <IconifyIcon icon="ant-design:eye-outlined" />
          预览表单
        </Button>
      </div>
    </div>

    <Tabs v-model:active-key="activeTab" class="manager-tabs">
      <!-- 属性结构编辑 -->
      <TabPane key="schema" tab="属性结构">
        <div class="schema-editor">
          <div class="schema-toolbar">
            <Button type="primary" @click="addField">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加字段
            </Button>
            <Button @click="importSchema">
              <IconifyIcon icon="ant-design:import-outlined" />
              导入结构
            </Button>
            <Button @click="exportSchema">
              <IconifyIcon icon="ant-design:export-outlined" />
              导出结构
            </Button>
          </div>

          <div class="schema-content">
            <div class="fields-list">
              <div
                v-for="(field, index) in schemaFields"
                :key="field.id"
                class="field-item"
                :class="{
                  'field-item--selected': selectedFieldId === field.id,
                }"
                @click="selectField(field.id)"
              >
                <div class="field-header">
                  <IconifyIcon :icon="getFieldTypeIcon(field.type)" />
                  <span class="field-name">{{
                    field.label || field.name
                  }}</span>
                  <Tag :color="field.required ? 'red' : 'blue'">
                    {{ field.required ? '必填' : '可选' }}
                  </Tag>
                </div>
                <div class="field-actions">
                  <Button
                    type="text"
                    size="small"
                    @click.stop="editField(index)"
                  >
                    <IconifyIcon icon="ant-design:edit-outlined" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    @click.stop="moveField(index, -1)"
                    :disabled="index === 0"
                  >
                    <IconifyIcon icon="ant-design:arrow-up-outlined" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    @click.stop="moveField(index, 1)"
                    :disabled="index === schemaFields.length - 1"
                  >
                    <IconifyIcon icon="ant-design:arrow-down-outlined" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    danger
                    @click.stop="removeField(index)"
                  >
                    <IconifyIcon icon="ant-design:delete-outlined" />
                  </Button>
                </div>
              </div>
            </div>

            <div class="field-editor" v-if="selectedFieldId">
              <FieldEditor
                :field="selectedField"
                @update="updateField"
                @delete="removeSelectedField"
              />
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 属性数据编辑 -->
      <TabPane key="data" tab="属性数据">
        <div class="data-editor">
          <div class="data-toolbar">
            <Button type="primary" @click="saveData" :loading="savingData">
              <IconifyIcon icon="ant-design:save-outlined" />
              保存数据
            </Button>
            <Button @click="resetData">
              <IconifyIcon icon="ant-design:reload-outlined" />
              重置数据
            </Button>
          </div>

          <div class="data-content">
            <!-- DynamicForm组件已删除，暂时显示占位符 -->
            <div class="form-placeholder">
              <p>动态表单组件正在开发中...</p>
              <p>当前属性数据: {{ JSON.stringify(propertyData, null, 2) }}</p>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 联动配置 -->
      <TabPane key="linkage" tab="联动配置">
        <div class="linkage-config">
          <div class="linkage-toolbar">
            <Button type="primary" @click="addLinkageRule">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加联动规则
            </Button>
            <Button @click="saveLinkageRules" :loading="savingLinkage">
              <IconifyIcon icon="ant-design:save-outlined" />
              保存配置
            </Button>
          </div>

          <div class="linkage-content">
            <div
              v-for="(rule, index) in linkageRules"
              :key="rule.id"
              class="linkage-rule"
            >
              <div class="rule-header">
                <span class="rule-name">{{ rule.name }}</span>
                <div class="rule-actions">
                  <Button
                    type="text"
                    size="small"
                    @click="editLinkageRule(index)"
                  >
                    <IconifyIcon icon="ant-design:edit-outlined" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    danger
                    @click="removeLinkageRule(index)"
                  >
                    <IconifyIcon icon="ant-design:delete-outlined" />
                  </Button>
                </div>
              </div>
              <div class="rule-content">
                <div class="rule-condition">
                  <strong>触发条件：</strong>
                  {{ formatCondition(rule.condition) }}
                </div>
                <div class="rule-action">
                  <strong>执行动作：</strong>
                  {{ formatAction(rule.action) }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </TabPane>

      <!-- 验证规则 -->
      <TabPane key="validation" tab="验证规则">
        <div class="validation-config">
          <div class="validation-toolbar">
            <Button type="primary" @click="addValidationRule">
              <IconifyIcon icon="ant-design:plus-outlined" />
              添加验证规则
            </Button>
            <Button @click="saveValidationRules" :loading="savingValidation">
              <IconifyIcon icon="ant-design:save-outlined" />
              保存规则
            </Button>
          </div>

          <div class="validation-content">
            <div
              v-for="(rule, index) in validationRules"
              :key="rule.id"
              class="validation-rule"
            >
              <div class="rule-header">
                <span class="rule-name">{{ rule.name }}</span>
                <Tag :color="rule.enabled ? 'green' : 'orange'">
                  {{ rule.enabled ? '启用' : '禁用' }}
                </Tag>
                <div class="rule-actions">
                  <Button
                    type="text"
                    size="small"
                    @click="editValidationRule(index)"
                  >
                    <IconifyIcon icon="ant-design:edit-outlined" />
                  </Button>
                  <Button
                    type="text"
                    size="small"
                    danger
                    @click="removeValidationRule(index)"
                  >
                    <IconifyIcon icon="ant-design:delete-outlined" />
                  </Button>
                </div>
              </div>
              <div class="rule-content">
                <div class="rule-expression">
                  <strong>验证表达式：</strong>
                  {{ rule.expression }}
                </div>
                <div class="rule-message">
                  <strong>错误消息：</strong>
                  {{ rule.message }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </TabPane>
    </Tabs>

    <!-- 字段编辑器模态框 -->
    <Modal
      v-model:visible="fieldEditorVisible"
      title="字段配置"
      width="600px"
      :footer="null"
    >
      <FieldEditor
        v-if="editingField"
        :field="editingField"
        @update="updateEditingField"
        @cancel="fieldEditorVisible = false"
      />
    </Modal>

    <!-- 联动规则编辑器模态框 -->
    <Modal
      v-model:visible="linkageEditorVisible"
      title="联动规则配置"
      width="800px"
      :footer="null"
    >
      <LinkageRuleEditor
        v-if="editingLinkageRule"
        :rule="editingLinkageRule"
        :fields="schemaFields"
        @update="updateLinkageRule"
        @cancel="linkageEditorVisible = false"
      />
    </Modal>

    <!-- 验证规则编辑器模态框 -->
    <Modal
      v-model:visible="validationEditorVisible"
      title="验证规则配置"
      width="600px"
      :footer="null"
    >
      <ValidationRuleEditor
        v-if="editingValidationRule"
        :rule="editingValidationRule"
        :fields="schemaFields"
        @update="updateValidationRule"
        @cancel="validationEditorVisible = false"
      />
    </Modal>

    <!-- 表单预览模态框 -->
    <Modal
      v-model:visible="previewVisible"
      title="表单预览"
      width="800px"
      :footer="null"
    >
      <div class="form-preview">
        <!-- DynamicForm组件已删除，暂时显示占位符 -->
        <div class="form-placeholder">
          <p>表单预览功能正在开发中...</p>
          <p>预览数据: {{ JSON.stringify(previewData, null, 2) }}</p>
        </div>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue';
import { Tabs, TabPane, Button, Modal, Tag, message } from 'ant-design-vue';
import { IconifyIcon } from '@vben/icons';

// 工具函数
const generateId = () => {
  return 'id_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
};

// 组件导入
import FieldEditor from './FieldEditor.vue';
// import DynamicForm from './DynamicForm.vue'; // 组件已删除
import LinkageRuleEditor from './LinkageRuleEditor.vue';
import ValidationRuleEditor from './ValidationRuleEditor.vue';

// Props
const props = defineProps<{
  resource: any;
}>();

// Emits
const emit = defineEmits<{
  update: [data: any];
}>();

// 响应式数据
const activeTab = ref('schema');
const saving = ref(false);
const savingData = ref(false);
const savingLinkage = ref(false);
const savingValidation = ref(false);

// 字段相关
const schemaFields = ref<any[]>([]);
const selectedFieldId = ref<string>('');
const fieldEditorVisible = ref(false);
const editingField = ref<any>(null);

// 数据相关
const propertyData = ref<Record<string, any>>({});
const previewData = ref<Record<string, any>>({});
const previewVisible = ref(false);

// 联动规则相关
const linkageRules = ref<any[]>([]);
const linkageEditorVisible = ref(false);
const editingLinkageRule = ref<any>(null);

// 验证规则相关
const validationRules = ref<any[]>([]);
const validationEditorVisible = ref(false);
const editingValidationRule = ref<any>(null);

// 计算属性
const selectedField = computed(() => {
  return schemaFields.value.find((field) => field.id === selectedFieldId.value);
});

// 方法
const getFieldTypeIcon = (type: string) => {
  const icons: Record<string, string> = {
    STRING: 'ant-design:font-size-outlined',
    NUMBER: 'ant-design:number-outlined',
    BOOLEAN: 'ant-design:check-square-outlined',
    DATE: 'ant-design:calendar-outlined',
    ENUM: 'ant-design:unordered-list-outlined',
    TEXTAREA: 'ant-design:file-text-outlined',
    FILE: 'ant-design:file-outlined',
  };
  return icons[type] || 'ant-design:question-outlined';
};

const addField = () => {
  const newField = {
    id: generateId(),
    name: '',
    label: '',
    type: 'STRING',
    required: false,
    defaultValue: '',
    validation: {},
    uiConfig: {},
  };
  schemaFields.value.push(newField);
  selectField(newField.id);
  fieldEditorVisible.value = true;
  editingField.value = { ...newField };
};

const selectField = (fieldId: string) => {
  selectedFieldId.value = fieldId;
};

const editField = (index: number) => {
  editingField.value = { ...schemaFields.value[index] };
  fieldEditorVisible.value = true;
};

const updateField = (field: any) => {
  const index = schemaFields.value.findIndex((f) => f.id === field.id);
  if (index !== -1) {
    schemaFields.value[index] = { ...field };
  }
  fieldEditorVisible.value = false;
  editingField.value = null;
};

const updateEditingField = (field: any) => {
  const index = schemaFields.value.findIndex((f) => f.id === field.id);
  if (index !== -1) {
    schemaFields.value[index] = { ...field };
  }
  fieldEditorVisible.value = false;
  editingField.value = null;
};

const removeField = (index: number) => {
  const field = schemaFields.value[index];
  if (selectedFieldId.value === field.id) {
    selectedFieldId.value = '';
  }
  schemaFields.value.splice(index, 1);
};

const removeSelectedField = () => {
  const index = schemaFields.value.findIndex(
    (f) => f.id === selectedFieldId.value,
  );
  if (index !== -1) {
    schemaFields.value.splice(index, 1);
    selectedFieldId.value = '';
  }
};

const moveField = (index: number, direction: number) => {
  const newIndex = index + direction;
  if (newIndex >= 0 && newIndex < schemaFields.value.length) {
    const field = schemaFields.value.splice(index, 1)[0];
    schemaFields.value.splice(newIndex, 0, field);
  }
};

const saveSchema = async () => {
  saving.value = true;
  try {
    // 将内部格式转换为VbenFormSchema格式
    const vbenSchema = schemaFields.value.map((field) => ({
      fieldName: field.name,
      label: field.label,
      component: field.uiConfig?.component || 'Input',
      componentProps: field.uiConfig?.componentProps || {},
      rules: field.required ? 'required' : undefined,
      defaultValue: field.defaultValue,
    }));

    const propertiesData = {
      schema: vbenSchema,
      data: propertyData.value,
    };

    // 这里调用API保存schema
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success('属性结构保存成功');
    emit('update', propertiesData);
  } catch (error) {
    message.error('保存失败');
  } finally {
    saving.value = false;
  }
};

const importSchema = () => {
  // 实现导入功能
  message.info('导入功能开发中');
};

const exportSchema = () => {
  // 实现导出功能
  const data = JSON.stringify(schemaFields.value, null, 2);
  const blob = new Blob([data], { type: 'application/json' });
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'property-schema.json';
  a.click();
  URL.revokeObjectURL(url);
  message.success('结构导出成功');
};

const onDataChange = (data: Record<string, any>) => {
  propertyData.value = { ...data };
};

const saveData = async () => {
  savingData.value = true;
  try {
    // 将内部格式转换为VbenFormSchema格式
    const vbenSchema = schemaFields.value.map((field) => ({
      fieldName: field.name,
      label: field.label,
      component: field.uiConfig?.component || 'Input',
      componentProps: field.uiConfig?.componentProps || {},
      rules: field.required ? 'required' : undefined,
      defaultValue: field.defaultValue,
    }));

    const propertiesData = {
      schema: vbenSchema,
      data: propertyData.value,
    };

    // 这里调用API保存数据
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success('属性数据保存成功');
    emit('update', propertiesData);
  } catch (error) {
    message.error('保存失败');
  } finally {
    savingData.value = false;
  }
};

const resetData = () => {
  propertyData.value = {};
  message.success('数据已重置');
};

const addLinkageRule = () => {
  const newRule = {
    id: generateId(),
    name: '',
    condition: {},
    action: {},
    enabled: true,
    enabledenabled,
  };
  linkageRules.value.push(newRule);
  editLinkageRule(linkageRules.value.length - 1);
};

const editLinkageRule = (index: number) => {
  editingLinkageRule.value = { ...linkageRules.value[index] };
  linkageEditorVisible.value = true;
};

const updateLinkageRule = (rule: any) => {
  const index = linkageRules.value.findIndex((r) => r.id === rule.id);
  if (index !== -1) {
    linkageRules.value[index] = { ...rule };
  }
  linkageEditorVisible.value = false;
  editingLinkageRule.value = null;
};

const removeLinkageRule = (index: number) => {
  linkageRules.value.splice(index, 1);
};

const saveLinkageRules = async () => {
  savingLinkage.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success('联动规则保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    savingLinkage.value = false;
  }
};

const addValidationRule = () => {
  const newRule = {
    id: generateId(),
    name: '',
    expression: '',
    message: '',
    enabled: true,
  };
  validationRules.value.push(newRule);
  editValidationRule(validationRules.value.length - 1);
};

const editValidationRule = (index: number) => {
  editingValidationRule.value = { ...validationRules.value[index] };
  validationEditorVisible.value = true;
};

const updateValidationRule = (rule: any) => {
  const index = validationRules.value.findIndex((r) => r.id === rule.id);
  if (index !== -1) {
    validationRules.value[index] = { ...rule };
  }
  validationEditorVisible.value = false;
  editingValidationRule.value = null;
};

const removeValidationRule = (index: number) => {
  validationRules.value.splice(index, 1);
};

const saveValidationRules = async () => {
  savingValidation.value = true;
  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));
    message.success('验证规则保存成功');
  } catch (error) {
    message.error('保存失败');
  } finally {
    savingValidation.value = false;
  }
};

const previewForm = () => {
  previewData.value = { ...propertyData.value };
  previewVisible.value = true;
};

const onPreviewDataChange = (data: Record<string, any>) => {
  previewData.value = { ...data };
};

const formatCondition = (condition: any) => {
  // 格式化条件显示
  return `${condition.field} ${condition.operator} ${condition.value}`;
};

const formatAction = (action: any) => {
  // 格式化动作显示
  return `${action.type}: ${action.target} = ${action.value}`;
};

// 初始化
onMounted(() => {
  // 从资源中加载现有的schema和数据
  if (props.resource?.properties) {
    try {
      const properties = JSON.parse(props.resource.properties);

      // 处理新的VbenFormSchema格式
      if (properties.schema && Array.isArray(properties.schema)) {
        // 新格式：VbenFormSchema
        schemaFields.value = properties.schema.map((field: any) => ({
          id: field.fieldName || generateId(),
          name: field.fieldName || '',
          label: field.label || '',
          type: getFieldTypeFromComponent(field.component),
          required: field.rules === 'required',
          defaultValue: field.defaultValue || '',
          validation: {},
          uiConfig: {
            component: field.component,
            componentProps: field.componentProps || {},
          },
        }));
        propertyData.value = properties.data || {};
      } else if (properties.schema && typeof properties.schema === 'object') {
        // 旧格式：对象格式
        const schemaObj = properties.schema;
        schemaFields.value = Object.keys(schemaObj.properties || {}).map(
          (key) => {
            const field = schemaObj.properties[key];
            return {
              id: key,
              name: key,
              label: field.label || key,
              type: field.type?.toUpperCase() || 'STRING',
              required: field.required || false,
              defaultValue: field.defaultValue || '',
              validation: field.validation || {},
              uiConfig: field.display || {},
            };
          },
        );
        propertyData.value = properties.data || {};
      } else {
        // 兼容旧格式：直接是字段数组
        schemaFields.value = properties.schema || [];
        propertyData.value = properties.data || properties;
      }
    } catch (error) {
      console.error('解析资源属性失败:', error);
    }
  }
});

// 根据组件类型获取字段类型
const getFieldTypeFromComponent = (component: string) => {
  const typeMap: Record<string, string> = {
    Input: 'STRING',
    InputNumber: 'NUMBER',
    Select: 'ENUM',
    Switch: 'BOOLEAN',
    DatePicker: 'DATE',
    Textarea: 'TEXTAREA',
    Upload: 'FILE',
  };
  return typeMap[component] || 'STRING';
};
</script>

<style lang="less" scoped>
.resource-property-manager {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .manager-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #f0f0f0;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 600;
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }

  .manager-tabs {
    :deep(.ant-tabs-content) {
      min-height: 500px;
    }
  }

  .schema-editor {
    .schema-toolbar {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafafa;
      border-radius: 6px;
    }

    .schema-content {
      display: flex;
      gap: 24px;
      min-height: 400px;

      .fields-list {
        flex: 0 0 300px;
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        overflow-y: auto;
        max-height: 500px;

        .field-item {
          padding: 12px;
          border-bottom: 1px solid #f0f0f0;
          cursor: pointer;
          transition: all 0.3s;

          &:hover {
            background: #f5f5f5;
          }

          &--selected {
            background: #e6f7ff;
            border-left: 3px solid #1890ff;
          }

          .field-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;

            .field-name {
              flex: 1;
              font-weight: 500;
            }
          }

          .field-actions {
            display: flex;
            gap: 4px;
            justify-content: flex-end;
          }
        }
      }

      .field-editor {
        flex: 1;
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        padding: 16px;
      }
    }
  }

  .data-editor {
    .data-toolbar {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafafa;
      border-radius: 6px;
    }

    .data-content {
      border: 1px solid #f0f0f0;
      border-radius: 6px;
      padding: 16px;
      min-height: 400px;
    }
  }

  .linkage-config {
    .linkage-toolbar {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafafa;
      border-radius: 6px;
    }

    .linkage-content {
      .linkage-rule {
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        margin-bottom: 12px;
        padding: 16px;

        .rule-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .rule-name {
            font-weight: 600;
            font-size: 14px;
          }

          .rule-actions {
            display: flex;
            gap: 4px;
          }
        }

        .rule-content {
          .rule-condition,
          .rule-action {
            margin-bottom: 8px;
            font-size: 13px;
            color: #666;
          }
        }
      }
    }
  }

  .validation-config {
    .validation-toolbar {
      display: flex;
      gap: 12px;
      margin-bottom: 16px;
      padding: 16px;
      background: #fafafa;
      border-radius: 6px;
    }

    .validation-content {
      .validation-rule {
        border: 1px solid #f0f0f0;
        border-radius: 6px;
        margin-bottom: 12px;
        padding: 16px;

        .rule-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 12px;

          .rule-name {
            font-weight: 600;
            font-size: 14px;
          }

          .rule-actions {
            display: flex;
            gap: 4px;
          }
        }

        .rule-content {
          .rule-expression,
          .rule-message {
            margin-bottom: 8px;
            font-size: 13px;
            color: #666;
          }
        }
      }
    }
  }

  .form-preview {
    padding: 16px;
    background: #fafafa;
    border-radius: 6px;
  }
}
</style>
